package com.focusai.efairy.ui.activity.project;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.focusai.efairy.R;
import com.focusai.efairy.model.manager.CacheManager;
import com.focusai.efairy.model.project.OnItemClickEditorListener;
import com.focusai.efairy.model.project.ProjectItem;
import com.focusai.efairy.model.request.DeleteDevFromProjectReqeust;
import com.focusai.efairy.model.request.GetDevMoreRequest;
import com.focusai.efairy.model.request.GetUserListRequest;
import com.focusai.efairy.model.response.ProjectManageResponse;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.adapter.base.RecycleViewDivider;
import com.focusai.efairy.ui.adapter.project.ProjectDevAdapter;
import com.focusai.efairy.ui.base.SwipeBackTipBaseActivity;
import com.focusai.efairy.ui.widget.SearchTittleView;
import com.focusai.efairy.utils.Constants;
import com.focusai.efairy.utils.ScreenUtil;
import com.mylhyl.crlayout.SwipeRefreshAdapterView;
import com.mylhyl.crlayout.SwipeRefreshRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by luo_guangwen on 2017/9/12.
 */

public class ProjectDevListActivity extends SwipeBackTipBaseActivity implements SwipeRefreshLayout.OnRefreshListener,
        SwipeRefreshAdapterView.OnListLoadListener {
    public static final String KEY_PROJECT_ID = "key_project_id";
    public static final String KEY_PROJECT_ITEM = "key_project_item";
    private static final int REQUEST_CODE_ADD = 0x11;
    private SwipeRefreshRecyclerView mRefreshRecyclerView;
    private SearchTittleView searchTittleView;
    private ProjectDevAdapter mAdapter;
    private List<ProjectManageResponse.DevItem> mList;
    private String projectId;
    private ProjectItem projectItem;
    private String mKeyword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_project_dev_list);
        initView();
        setDefaultValues();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuItem1 = menu.add(MENU_GROUP_ID, MENU_ITEM_ADD, 0, R.string.add).setTitle(R.string.add);
        MenuItemCompat.setShowAsAction(menuItem1, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == MENU_ITEM_ADD) {
            Intent intent = new Intent(getContext(), ProjectAddDeviceActivity.class);
            intent.putExtra(ProjectAddDeviceActivity.KEY_PROJECT_ID, projectId);
            startActivityForResult(intent, REQUEST_CODE_ADD);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void initView() {
        mRefreshRecyclerView = findView(R.id.swipe_recyce_view);
        searchTittleView = findView(R.id.view_tittle_search);

    }

    @Override
    protected void setDefaultValues() {
        setCenterTitleName("设备列表");
        if (getIntent() != null) {
            projectId = getIntent().getStringExtra(KEY_PROJECT_ID);
            projectItem = (ProjectItem) getIntent().getSerializableExtra(KEY_PROJECT_ITEM);
        }
        if (TextUtils.isEmpty(projectId)) {
            showToast("项目id为空");
            finish();
        }
        mAdapter = new ProjectDevAdapter(projectItem != null
                && !String.valueOf(projectItem.efairyproject_creator_id).equals(CacheManager.getUserId()));
        mList = new ArrayList<>();
        mRefreshRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRefreshRecyclerView.setAdapter(mAdapter);
        mRefreshRecyclerView.getScrollView().addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.VERTICAL, ScreenUtil.dp2pix(15), getResources().getColor(R.color.main_line_gray)));
        mAdapter.refreshData(mList);
        mRefreshRecyclerView.setOnListLoadListener(this);
        mRefreshRecyclerView.setOnRefreshListener(this);

        mAdapter.setListener(new OnItemClickEditorListener<ProjectManageResponse.DevItem>() {
            @Override
            public void onEdit(ProjectManageResponse.DevItem item, int position) {
                if (projectItem != null && !String.valueOf(projectItem.efairyproject_creator_id).equals(CacheManager.getUserId())) {
                    showToast(R.string.no_right_do);
                    return;
                }
                Intent intent = new Intent(getContext(), ProjectAddDeviceActivity.class);
                intent.putExtra(ProjectAddDeviceActivity.KEY_DEV_ITEM, item);
                intent.putExtra(ProjectAddDeviceActivity.OPENTYPE, true);
                intent.putExtra(ProjectAddDeviceActivity.KEY_PROJECT_ID, projectId);
                intent.putExtra(Constants.KEY_DETAIL, false);
                startActivityForResult(intent, REQUEST_CODE_ADD);
            }

            @Override
            public void onDelete(ProjectManageResponse.DevItem item, int position) {
                if (projectItem != null && !String.valueOf(projectItem.efairyproject_creator_id).equals(CacheManager.getUserId())) {
                    showToast(R.string.no_right_do);
                    return;
                }
                showDeleteDialog(item);
            }

            @Override
            public void onItemClick(ProjectManageResponse.DevItem item, int position) {
                Intent intent = new Intent(getContext(), ProjectAddDeviceActivity.class);
                intent.putExtra(ProjectAddDeviceActivity.KEY_DEV_ITEM, item);
                intent.putExtra(ProjectAddDeviceActivity.OPENTYPE, false);
                intent.putExtra(ProjectAddDeviceActivity.KEY_PROJECT_ID, projectId);
                intent.putExtra(Constants.KEY_DETAIL, true);
                startActivity(intent);
            }
        });
        mRefreshRecyclerView.setRefreshing(true);
        searchTittleView.setSearchListener(new SearchTittleView.OnSearchListener() {
            @Override
            public void onStartQuery(String keywork, boolean hideInput) {
                if (hideInput) {
                    hideSoftInput();
                }
                mKeyword = keywork;
                mRefreshRecyclerView.setRefreshing(true);
            }

            @Override
            public void onCancalBackClick() {
                getToolbar().setVisibility(View.VISIBLE);
                hideSoftInput();
                mKeyword = "";
                mRefreshRecyclerView.setRefreshing(true);

            }

            @Override
            public void onEnterInputKeyWork() {
                getToolbar().setVisibility(View.GONE);
                mKeyword = "";
            }
        });
    }

    @Override
    public void onRefresh() {
        refresh();
    }

    @Override
    public void onListLoad() {
        loadMore();
    }

    private void refresh() {
        HttpManager.getInstance().sendRequest(new GetDevMoreRequest(projectId, 0, mKeyword,
                new Response.Listener<ProjectManageResponse.DevItems>() {
                    @Override
                    protected void onSuccess(ProjectManageResponse.DevItems response) {
                        if (response != null && response.device_list != null) {
                            mList.clear();
                            mList.addAll(response.device_list);
                            mAdapter.notifyDataSetChanged();
                            if (GetUserListRequest.size > mList.size()) {
                                mRefreshRecyclerView.setEnabledLoad(false);
                            } else {
                                mRefreshRecyclerView.setEnabledLoad(true);
                            }
                            mRefreshRecyclerView.setRefreshing(false);
                        }
                        showTip(mList);
                    }

                    @Override
                    protected void onFail(NetworkException exception) {
                        doException(exception);
                        mRefreshRecyclerView.setRefreshing(false);
                        showTip(mList);
                    }
                }));
    }

    private void loadMore() {
        if (mList.size() == 0) {
            mRefreshRecyclerView.setLoading(false);
            return;
        }
        HttpManager.getInstance().sendRequest(new GetDevMoreRequest(projectId, mList.get(mList.size() - 1).efairydevice_id, mKeyword,
                new Response.Listener<ProjectManageResponse.DevItems>() {
                    @Override
                    protected void onSuccess(ProjectManageResponse.DevItems response) {
                        if (response != null && response.device_list != null) {

                            mList.addAll(response.device_list);
                            mAdapter.notifyDataSetChanged();
                            if (mList.size() == response.efairyproject_total_devices) {
                                mRefreshRecyclerView.setEnabledLoad(false);
                            } else {
                                mRefreshRecyclerView.setEnabledLoad(true);
                            }
                            mRefreshRecyclerView.setLoading(false);
                        }
                    }

                    @Override
                    protected void onFail(NetworkException exception) {
                        doException(exception);
                        mRefreshRecyclerView.setLoading(false);
                    }
                }));
    }

    private void delete(final ProjectManageResponse.DevItem item) {
        showSingleDialog("正在删除设备..");
        DeleteDevFromProjectReqeust.UpLoadEntry entry = new DeleteDevFromProjectReqeust.UpLoadEntry();
        entry.efairyproject_id = projectId;
        entry.efairydevice_id_list = new ArrayList<Long>();
        entry.efairydevice_id_list.add(item.efairydevice_id);
        HttpManager.getInstance().sendRequest(new DeleteDevFromProjectReqeust(entry, new Response.Listener<String>() {
            @Override
            protected void onSuccess(String response) {
                closeSingleDialog();
                mList.remove(item);
                mAdapter.notifyDataSetChanged();
                setResult(RESULT_OK);
            }

            @Override
            protected void onFail(NetworkException exception) {
                closeSingleDialog();
                doException(exception);
            }
        }));
    }

    private void showDeleteDialog(final ProjectManageResponse.DevItem item) {
        AlertDialog dialog = new AlertDialog.Builder(getContext()).create();
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.sure), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                delete(item);
            }
        });
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.cancal), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        dialog.setCancelable(true);
        dialog.setMessage(getString(R.string.make_sure_delete_dev));
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_ADD:
                    mRefreshRecyclerView.setRefreshing(true);
                    setResult(RESULT_OK);
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (searchTittleView.onKeyDown(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
